<template>
  <div id="app" class="upload-section">
    <div class="upload-card">
      <h3 class="title">上传 PDF 文件</h3>
      <input
          type="file"
          accept=".pdf"
          id="file-upload"
          @change="handleFileUpload"
          class="file-input"
      />
      <label for="file-upload" class="upload-label">点击上传</label>
      <p v-if="errorMessage" class="error">{{ errorMessage }}</p>

      <!-- 文件预览 -->
      <div v-if="uploadedFile" class="preview-section">
        <h4>已上传文件：</h4>
        <p class="file-name">{{ uploadedFile.name }}</p>

        <!-- PDF 预览 -->
        <iframe
            v-if="previewUrl"
            :src="previewUrl"
            class="pdf-preview"
        ></iframe>

        <el-button @click="uploadToServer" type="primary" style="margin-top: 10px">
          上传到服务器
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { BASE_URL } from "@/config";

export default {
  data() {
    return {
      uploadedFile: null, // 上传的文件
      base64Data: "", // 文件的 Base64 数据
      previewUrl: "", // PDF 文件的预览 URL
      errorMessage: "", // 错误消息
    };
  },
  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0]; // 获取文件
      if (!file) {
        this.errorMessage = "请选择一个文件";
        return;
      }

      // 检查文件格式
      if (!file.type.includes("application/pdf")) {
        this.errorMessage = "只支持上传 PDF 格式的文件";
        return;
      }

      this.errorMessage = ""; // 清除错误消息
      this.uploadedFile = file;

      // 生成 PDF 预览 URL
      this.previewUrl = URL.createObjectURL(file);

      // 生成 Base64 数据
      const reader = new FileReader();
      reader.onload = (e) => {
        this.base64Data = e.target.result.split(",")[1]; // 去掉 "data:application/pdf;base64," 只保留 Base64 部分
        console.log("Base64 数据:", this.base64Data);
      };
      reader.readAsDataURL(file);
    },

    async uploadToServer() {
      if (!this.base64Data) {
        this.$message.error("请先上传文件！");
        return;
      }

      try {
        // 上传文件到后端
        const response = await axios.post(`${BASE_URL}/homework/submission`, {
          stu_id: window.sessionStorage.getItem("userId"),
          homework_id: this.$route.query.homework_id,
          content: this.base64Data, // Base64 数据
        });

        if (response.status===200) {
          this.$message.success("文件上传成功！");
        } else {
          this.$message.error("文件上传失败！");
        }
      } catch (error) {
        console.error("上传失败:", error);
        this.$message.error("网络错误！");
      }
    },
  },
};
</script>

<style scoped>
.upload-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f4f8;
  font-family: "Arial", sans-serif;
}

.upload-card {
  background-color: white;
  padding: 30px 40px;
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 600px;
  width: 100%;
}

.title {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.file-input {
  display: none;
}

.upload-label {
  display: inline-block;
  padding: 10px 20px;
  color: white;
  background-color: #007bff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  margin-top: 10px;
  transition: background-color 0.3s ease;
}

.upload-label:hover {
  background-color: #0056b3;
}

.error {
  color: red;
  font-size: 14px;
  margin-top: 10px;
}

.preview-section {
  margin-top: 20px;
  text-align: left;
}

.file-name {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.pdf-preview {
  width: 100%;
  height: 500px;
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
